<template>
	<view class="company-info">
		<!-- 顶部固定导航栏和标题区域 -->
		<view class="header-container">
			<!-- 顶部按钮区域：返回按钮和编辑/保存按钮 -->
			<view class="header-buttons">
				<!-- 返回按钮：使用图标字体显示左箭头 -->
				<tn-button backgroundColor="transparent" style="color: #333; width: 10vw; height: 10vw; font-size: 5vw;"
					:border="false" @click="handleReturn">
					<text class="tn-icon-left"></text>
				</tn-button>

				<!-- 编辑/保存按钮：根据编辑状态切换显示文本和颜色 -->
				<tn-button :backgroundColor="isEditing ? '#4CAF50' : '#2196F3'" size="sm"
					style="color: white; width: auto; height: 10vw; font-size: 4vw; border-radius: 5px;" :border="false"
					@click="handleEditToggle">
					{{ isEditing ? '保存' : '编辑' }}
				</tn-button>
			</view>
			<!-- 页面标题 -->
			<view class="page-title">公司资料</view>
		</view>

		<!-- 公司信息展示区域 -->
		<view class="company-info-section">
			<view class="company-info-item" v-for="key in orderedKeys" :key="key">
				<view class="info-label">{{ labels[key] }}：</view>
				<view class="info-value" v-if="!isEditing">{{ companyInfo[key] || '暂无数据' }}</view>
				<view class="info-input" v-else>
					<!-- 类别选择器 -->
					<picker v-if="key === 'category'" mode="selector" :range="categoryNames"
						:value="getCategoryIndex()" @change="handleCategoryChange">
						<view class="picker-value">
							<text>{{ companyInfo.category || '请选择公司类别' }}</text>
							<text class="picker-arrow"></text>
						</view>
					</picker>
					<!-- 多行文本输入框 -->
					<textarea v-else-if="['businessScope', 'address'].includes(key)" v-model="companyInfo[key]"
						class="textarea-input"></textarea>
					<!-- 日期选择器 -->
					<input v-else-if="key === 'establishedDate'" type="date" v-model="companyInfo[key]"
						class="normal-input" />
					<!-- 普通文本输入框 -->
					<input v-else type="text" v-model="companyInfo[key]" class="normal-input" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 控制页面是否处于编辑状态
				isEditing: false,

				// 公司基本信息数据
				companyInfo: {
					name: "",
					userId: uni.getStorageSync('userInfo').id,
					categoryId: 0,
					category: "",
					establishedDate: "",
					address: "",
					businessScope: "",
					phone: "",
					email: "",
					website: "",
					products: ""
				},

				// 用于存储编辑前的原始数据，用于取消编辑时恢复
				originalInfo: null,

				// 公司类别选项配置
				categoryOptions: [],

				// 用于picker显示的类别名称数组
				categoryNames: [],

				// 字段标签
				labels: {
					name: "公司名称",
					category: "公司类别",
					establishedDate: "成立时间",
					address: "注册地址",
					businessScope: "经营范围",
					phone: "公司电话",
					email: "公司邮箱",
					website: "官方网站",
					products: "主要产品/服务"
				},

				// 字段显示顺序
				orderedKeys: [
					'name',
					'category',
					'establishedDate',
					'address',
					'businessScope',
					'phone',
					'email',
					'website',
					'products'
				]
			};
		},

		mounted() {
			this.getCategory();
		},

		methods: {
			// 处理返回按钮点击
			// 如果正在编辑，会提示是否放弃修改
			handleReturn() {
				if (this.isEditing) {
					uni.showModal({
						title: '提示',
						content: '确定要放弃修改吗？',
						success: (res) => {
							if (res.confirm) {
								this.cancelEdit();
								uni.navigateBack();
							}
						}
					});
				} else {
					uni.navigateBack();
				}
			},

			// 处理编辑/保存按钮点击
			// 切换编辑状态或保存修改
			handleEditToggle() {
				if (!this.isEditing) {
					// 进入编辑模式，保存当前数据
					this.originalInfo = JSON.parse(JSON.stringify(this.companyInfo));
					this.isEditing = true;
				} else {
					// 保存修改
					this.saveChanges();
				}
			},

			// 取消编辑，恢复到原始数据状态
			cancelEdit() {
				if (this.originalInfo) {
					this.companyInfo = JSON.parse(JSON.stringify(this.originalInfo));
				}
				this.isEditing = false;
				this.originalInfo = null;
			},

			// 保存修改的数据
			// 调用后端接口并处理结果
			saveChanges() {
				uni.request({
					url: this.baseUrl + "/wx/companyInfo/save",
					method: 'POST',
					data: this.companyInfo,
					success: (res) => {
						if (res.statusCode === 200 && res.data.errno === 0) {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
							this.isEditing = false;
							this.originalInfo = null;
						} else {
							uni.showToast({
								title: res.data.msg || '保存失败',
								icon: 'error'
							});
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: '保存失败',
							icon: 'error'
						});
					}
				});
			},

			// 获取类别数据
			getCategory() {
				uni.request({
					url: this.baseUrl + "/admin/category/list",
					success: (res) => {
						const list = res.data.data.list.filter(item => (item.id === 1036065));
						if (list.length > 0 && list[0].children) {
							this.categoryOptions = list[0].children;
							this.categoryNames = this.categoryOptions.map(item => item.name);
							this.getCompanyInfo();
						}
					},
					fail: (error) => {
						console.error('获取类别失败:', error);
						this.getCompanyInfo();
					}
				});
			},

			// 获取公司信息
			getCompanyInfo() {
				const userId = uni.getStorageSync('userInfo').id;
				console.log(userId);
				uni.request({
					url: this.baseUrl + "/wx/companyInfo/getCompanyInfo",
					method: 'GET',
					data: { userId },
					success: (res) => {
						if (res.statusCode === 200 && res.data.errno === 0 && res.data.data) {
							this.companyInfo = res.data.data;
							this.updateCategoryName();
						}
					},
					fail: (error) => {
						console.error('获取公司信息失败:', error);
					}
				});
			},
			
			// 更新类别名称
			updateCategoryName() {
				if (this.companyInfo.categoryId && this.categoryOptions.length > 0) {
					const category = this.categoryOptions.find(item => item.id === this.companyInfo.categoryId);
					if (category) {
						this.companyInfo.category = category.name;
					}
				}
			},

			// 获取类别索引
			getCategoryIndex() {
				const index = this.categoryNames.findIndex(name => name === this.companyInfo.category);
				return index >= 0 ? index : 0;
			},

			// 处理类别选择变化
			handleCategoryChange(e) {
				const index = e.detail.value;
				if (index >= 0 && index < this.categoryOptions.length) {
					const selectedCategory = this.categoryOptions[index];
					console.log('选择的类别:', selectedCategory);
					
					// 更新数据
					this.companyInfo.category = selectedCategory.name;
					this.companyInfo.categoryId = selectedCategory.id;
					
					// 延迟更新视图，确保数据已经被正确设置
					setTimeout(() => {
						this.$forceUpdate();
					}, 50);
				}
			}
		}
	};
</script>

<style scoped>
	/* 修改导航栏和标题容器样式 */
	.header-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 99;
		background-color: #fff;
	}

	.header-buttons {
		padding: 4vw 4vw;
		margin: 6vw 0 0 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.page-title {
		font-size: 4.5vw;
		font-weight: bold;
		text-align: center;
		padding: 1vw 0;
		margin-top: -2.5vw;
		/* 增加负边距，让标题更靠近导航栏 */
	}

	/* 调整内容区域，为固定导航栏留出空间 */
	.company-info-section {
		margin-top: calc(24vw + 3vw);
		/* 减少上边距：导航栏高度 + margin */
		margin-left: 3vw;
		margin-right: 3vw;
		margin-bottom: 3vw;
		padding: 0;
		background-color: white;
		border-radius: 8px;
		box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.05);
		flex: 1;
		overflow-y: auto;
	}

	.company-info-item {
		margin: 0;
		padding: 3vw 4vw;
		border-bottom: 1px solid #eee;
	}

	.company-info-item:last-child {
		border-bottom: none;
	}

	.info-label {
		font-size: 3.8vw;
		color: #666;
		margin-bottom: 2vw;
	}

	.info-value {
		font-size: 4vw;
		color: #333;
		line-height: 1.6;
		padding: 0;
	}

	.info-input {
		width: 100%;
		margin-top: 2vw;
	}

	.normal-input {
		border: 1px solid #e0e0e0;
		background-color: #fafafa;
		padding: 3vw;
		font-size: 4vw;
		height: 11vw;
		border-radius: 4px;
	}

	.textarea-input {
		border: 1px solid #e0e0e0;
		background-color: #fafafa;
		padding: 3vw;
		font-size: 4vw;
		min-height: 30vw;
		border-radius: 4px;
		line-height: 1.5;
	}

	.normal-input:focus,
	.textarea-input:focus {
		border-color: #2196F3;
		background-color: #fff;
		outline: none;
	}

	tn-button {
		font-size: 5vw;
		font-family: "宋体", SimSun, sans-serif;
	}

	.header-buttons tn-button:first-child {
		width: 10vw;
		height: 10vw;
		font-size: 5vw;
		box-shadow: none;
		display: flex;
		align-items: center;
		justify-content: center;
		background: transparent !important;
		color: #333 !important;
		border-radius: 0;
	}

	.header-buttons tn-button:last-child {
		height: 8vw;
		font-size: 3.5vw;
		border-radius: 4px;
		box-shadow: none;
		min-width: 16vw;
		padding: 0 3vw;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 修改 picker 相关样式 */
	.picker-value {
		border: 1px solid #e0e0e0;
		background-color: #fafafa;
		padding: 0 3vw;
		font-size: 4vw;
		height: 11vw;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.picker-arrow {
		display: inline-block;
		width: 0;
		height: 0;
		border-left: 1.5vw solid transparent;
		border-right: 1.5vw solid transparent;
		border-top: 1.5vw solid #666;
		margin-left: 2vw;
	}

	/* 删除之前的样式 */
	.picker-value::after {
		display: none;
	}

	/* 删除不需要的类 */
	select.normal-input {
		display: none;
	}
</style>